<?php
namespace ImiApp\ApiServer\Controller;

use Imi\Controller\HttpController;
use Imi\Db\Db;
use Imi\Server\Route\Annotation\Action;
use Imi\Server\Route\Annotation\Controller;

/**
 * @Controller("/queryBuilder/")
 */
class QueryBuilderController extends HttpController
{
    /**
     * @Action
     *
     * @param string $a
     * @return void
     */
    public function create($a)
    {
        $query = Db::query();
        $result = $query->from('tb_test')->insert([
            'a' =>  $a,
        ]);
        return [
            'id'    =>  $result->getLastInsertId(),
        ];
    }

    /**
     * @Action
     *
     * @param int $id
     * @param string $a
     * @return void
     */
    public function update($id, $a)
    {
        $query = Db::query();
        $result = $query->table('tb_test')
                        // ->where('id', '=', $id)
                        ->whereEx([
                            'id'    =>  $id,
                        ])
                        ->update([
                            'a' =>  $a,
                        ]);
        return [
            'rowCount'  =>  $result->getAffectedRows(),
        ];
    }

    /**
     * @Action
     *
     * @param int $id
     * @return void
     */
    public function get($id)
    {
        return [
            'data'  =>  Db::query()->from('tb_test')->where('id', '=', $id)->select()->get(),
        ];
    }

    /**
     * @Action
     *
     * @return void
     */
    public function query()
    {
        return [
            'list'  =>  Db::query()->from('tb_test')->select()->getArray(),
        ];
    }

    /**
     * @Action
     *
     * @param int $id
     * @return void
     */
    public function delete($id)
    {
        return [
            'rowCount'  =>  Db::query()->from('tb_test')->where('id', '=', $id)->delete()->getAffectedRows(),
        ];
    }

}
